package com.bkhech.spring.security.example.util;

import cn.hutool.core.util.StrUtil;
import com.bkhech.spring.security.example.domain.LoginUser;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 安全服务工具类
 *
 * @author guowm
 * @date 2023/1/11
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SecurityFrameworkUtils {
    public static final String AUTHORIZATION_BEARER = "Bearer";

    /**
     * 从请求中，获得认证 token
     *
     * @param request 请求
     * @param header  认证 token 对应的 Header 名字
     * @return 认证 token
     */
    public static String obtainAuthorization(HttpServletRequest request, String header) {
        final String authorization = request.getHeader(header);
        if (StrUtil.isEmpty(authorization)) {
            return null;
        }

        final int index = authorization.indexOf(AUTHORIZATION_BEARER + StrUtil.SPACE);
        if (index == -1) {
            return null;
        }
        return authorization.substring(index + 7).trim();
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    public static LoginUser getLoginUser() {
        final SecurityContext context = SecurityContextHolder.getContext();
        if (Objects.isNull(context)) {
            return null;
        }
        final Authentication authentication = context.getAuthentication();
        if (Objects.isNull(authentication)) {
            return null;
        }
        final Object principal = authentication.getPrincipal();
        if (principal instanceof LoginUser) {
            return ((LoginUser) principal);
        }
        return null;
    }

    @Nullable
    public static Long getLoginUserId() {
        final LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getId() : null;
    }

    /**
     * 设置当前用户
     *
     * @param loginUser 登录用户
     * @param request   请求
     */
    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
        // 创建 Authentication， 并设置到上下文
        Authentication authentication = buildAuthentication(loginUser, request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {
        // 创建 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getScopes().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }
}
